
#include "file_operation.h"
#include <cstdint>
#include <fcntl.h>
#include <strings.h>
#include <sys/file.h>
#include <unistd.h>

bool InitFileOperation(FileOperation &file_opertion, int mode)
{

	bzero(file_opertion.m_buffer, sizeof(file_opertion.m_buffer));

	switch (mode)
	{
		case 1:
		{
			file_opertion.m_file_handle = open(file_opertion.m_file_name.c_str(), O_RDONLY, 0666);
			if (file_opertion.m_file_handle < 0)
			{
				file_opertion.m_file_handle = -1;
				return false;
			}
			break;
		}
		case 2:
		{
			file_opertion.m_file_handle = open(file_opertion.m_file_name.c_str(), O_CREAT | O_RDWR, 0666);
			if (file_opertion.m_file_handle < 0)
			{
				file_opertion.m_file_handle = -1;
				return false;
			}
			break;
		}
	}
	return true;
}



void FreeFileOperation(FileOperation &file_operation)
{
	if (file_operation.m_file_handle >= 0)
	{
		close(file_operation.m_file_handle);
	}
}

int GetFileContent(FileOperation &file_opertion)
{

	if (file_opertion.m_file_handle >= 0)
	{
		bzero(file_opertion.m_buffer, sizeof(file_opertion.m_buffer));
		int size = read(file_opertion.m_file_handle, file_opertion.m_buffer + 4, sizeof(file_opertion.m_buffer) - 4);
		return size;
	}
	else 
	{
		return 0;
	}
}

void SaveFileContent(FileOperation &file_operation, uint8_t *data, int length)
{
	if (file_operation.m_file_handle >= 0)
	{
		write(file_operation.m_file_handle, data, length);
	}
}